package com.hm.health.Fragment;

import android.os.Bundle;
import android.view.View;

import com.goodix.fragment.BaseFragment;
import com.goodix.libromablecom.sdk.cardiff.CardiffConstants;
import com.goodix.comsdk.entity.MeasureResult;
import com.goodix.comsdk.sdk.OnHBDDataListener;
import com.goodix.libromablecom.sdk.cardiff.arguments.GetArgumentsKeyEnum;
import com.goodix.libromablecom.sdk.cardiff.arguments.StartArgumentsKeyEnum;
import com.hm.health.MyApplication;
import com.hm.health.R;
import com.hm.health.Utils.Constans;
import com.hm.health.View.ECGChartView;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created by chenshi on 2019/12/29.
 */

public class ECGChartFragment extends BaseFragment{
    public static final String TAG = "ECGChartFragment";

    private ECGChartView mECGChartView;
    private String mFunctionName;
    private boolean mStartDrawEcgChart = false;
    private float[] mBuffer = new float[1000];
    private int[] mLeadState = new int[1000];
    private AtomicInteger mCount = new AtomicInteger(0);

    public static ECGChartFragment newInstance(String functionName) {
        ECGChartFragment fragment = new ECGChartFragment();
        Bundle bundle = new Bundle();
        bundle.putString(Constans.ARGS_FUNCTION_NAME, functionName);
        fragment.setArguments(bundle);
        return  fragment;
    }

    @Override
    public int getCreateViewLayoutResId() {
        return R.layout.fragment_ecg_chart;
    }

    @Override
    public void initData() {
        mFunctionName = getArguments().getString(Constans.ARGS_FUNCTION_NAME);
    }

    @Override
    public void findView(View inflateView, Bundle savedInstanceState) {
        mECGChartView = inflateView.findViewById(R.id.chart_ecg);
        int sampleRate = Integer.decode(MyApplication.getHBDTestClient()
                .getRunTimeFlag(GetArgumentsKeyEnum.ARG_GET_SAMPLE_RATE));
        if (sampleRate <= 0) sampleRate = 500;
        mECGChartView.setFrequency(3,sampleRate);
    }

    @Override
    public void initView(View inflateView, Bundle savedInstanceState) {
        startDrawEcgChart();
    }

    private void startDrawEcgChart() {
        mCount.set(0);
        ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
        scheduledExecutorService.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        synchronized (mCount) {
                            for (int i = 0; i < mCount.get(); ++i) {
                                mECGChartView.addPointWithFlag(mBuffer[i], mLeadState[i]);
                            }
                            mCount.set(0);
                        }
                        mECGChartView.invalidate();
                    }
                });
            }
        }, 1000, 40, TimeUnit.MILLISECONDS);
    }

    private OnHBDDataListener mOnHBDDataListener = new OnHBDDataListener() {
        @Override
        public void onDataChanged(String dataType, int[] dataArr) {

            if (!isAdded()) {
                return;
            }

            if (null == dataArr || dataArr.length == 0) {
                return;
            }

            if (StartArgumentsKeyEnum.AppFunction_ECG_CONTOL.equalsIgnoreCase(dataType)) {
                mStartDrawEcgChart = (dataArr[0] == 1);
                mECGChartView.clearData();
                mCount.set(0);
            }

            if (!mStartDrawEcgChart) {
                // stop draw ecg chart
                return;
            }

            if (mFunctionName.compareToIgnoreCase(dataType) == 0) {
                float value = dataArr[CardiffConstants.RawdataColumn.ALGO_RESULT0.ordinal()] / 100f;
                int lead = dataArr[CardiffConstants.RawdataColumn.FLAG4.ordinal()];
                synchronized (mCount) {
                    if (mCount.get() >= mBuffer.length) {
                        mCount.set(0);
                    }
                    mBuffer[mCount.get()] = value;
                    mLeadState[mCount.get()] = lead;
                    mCount.getAndAdd(1);
                }
            }
        }

        @Override
        public void onMeasureResult(MeasureResult result) {

        }
    };

    @Override
    public void onResume() {
        super.onResume();
        MyApplication.getHBDTestClient().registerHBDDataListener(mOnHBDDataListener);
    }

    @Override
    public void onPause() {
        super.onPause();
        MyApplication.getHBDTestClient().unRegisterHBDDataListener(mOnHBDDataListener);
    }
}
